public class extensionControllerClass
{
    //For Official Application Form Viewer Variables....
    public List<Party_Information__c> Shareholders {get; set;}
    public List<Location_Booking_Information__c> Locations {get; set;}
    public List<Account_Activity__c> Activities {get; set;}
    //..............
    Public Boolean chamberPage1Flag {get;set;}
    Public Boolean chamberPage2Flag {get;set;}
    Public Boolean chamberPartnerAmendmentFlag {get;set;} 
    Public Boolean chamberActivityAmendmentFlag {get;set;}   
    //For Invoice PDF Viewer Variables....
    public List<Invoice__c> invoiceList {get;set;}
    public Boolean redirectToReceiptPdfFlag {get;set;}
    public Boolean refreshPage {get;set;}
    //For Payment Generation Variables...
    Public List<ReceiptWrapper> ReceiptWrapperList {get; set;}
    public Payment__c NewPayment {get; set;}
    public Boolean actionbuttonADD {get; set;}
    public Boolean actionbuttonEdit {get; set;}
    public string RowIndex {get; set;}
    public string RowIndex2 {get; set;}
    public string ReceiptID {get; set;}
    public string receiptName {get;set;}
    public string receiptAccountId {get;set;}
    public Decimal receiptBalance {get;set;}
    public Boolean confirmationbuttonFlag {get;set;}
    public Boolean pdfbuttonFlag {get;set;}
    public Boolean paymentConfirmationFlag {get;set;}
    public DateTime CurrentTime {get;set;}
    public DateTime CurrentTimeReceipt {get;set;}
    //For Receipt PDF Viewer Variables...
    public List<Receipt__c> receiptPDFViewerList {get;set;}
    public List<Invoice_Line_Item__c> invoiceLineItemList {get;set;}
    Public Receipt__c receiptObject {get;set;}
    //For Tenancy Contract PDF Viewer Variables...
    public List<Tenancy_Contract__c> tenancyContractViewerList{get;set;}
    public string numberToWordString {get;set;}    
    //For Generating the Share Ownership PDF Viewer Variables...
    Public Account accountForArticlesObject {get;set;}
    //public List<Party_Information__c> partyInformationList {get;set;}
    public List<Share_Ownership__c> partyInformationList {get;set;}
    Public List<Wrapper_Shareholders> ListShareholders {get; set;}
    //public Party_Information__c partyManagerObject {get;set;}
    public Share_Ownership__c partyManagerObject {get;set;}
    
    //For Generating the License....
    public Account accountForLicenseList {get;set;}
    public List<Share_Ownership__c> sharedOwnerLicenseList {get;set;}
    
    //For Generating the Chamber PDF Viewer...
    public Account accountForChamberObject {get;set;}
    Public Amendment__c amendmentForChamberObject {get;set;}
      
    //For Constructor....
    public extensionControllerClass()
    {
        CurrentTime = Datetime.now().addhours(4);
        receiptObject = new Receipt__c();
    }
    public extensionControllerClass(ApexPages.StandardController controller) 
    {
         chamberPage2Flag = false;
         chamberPage1Flag = true;
         chamberPartnerAmendmentFlag = false;
         refreshPage =false; 
         redirectToReceiptPdfFlag= false;
         chamberActivityAmendmentFlag= false;
         paymentConfirmationFlag = false;
         confirmationbuttonFlag = false;
         pdfbuttonFlag = false;
         receiptObject = new Receipt__c();
         numberToWordString = '';
         //Initializing the Object...
         CurrentTime = Datetime.now().addhours(4);
         
    }
    
    //Generate the PDF for the Official Application Form Methods...
    public PageReference generateOfficialAppFormMethod()
    {
        Shareholders = new List<Party_Information__c>();
        Shareholders = [SELECT Name_PDF__c, Email_PDF__c, Mobile_Phone_PDF__c , Work_Phone_PDF__c,Address_PDF__c,Nationality_PDF__c,id, Account__c, First_Name__c, Role__c, Name, Title__c, Country__r.Name, Address__c, Email_Address__c, Land_Number__c, Mobile_Number__c FROM Party_Information__c WHERE Account__c = :Apexpages.CurrentPage().getParameters().get('id') AND Role__c INCLUDES('Shareholder')  Order by First_Name__c];
        Locations = [SELECT id, Account__c, Location__r.Name,Location__r.Location_Type__c FROM Location_Booking_Information__c WHERE Account__c = :Apexpages.CurrentPage().getParameters().get('id')];
        Activities = [SELECT id, Active__c,Account__c, Activity__r.Name FROM Account_Activity__c WHERE Account__c = :ApexPages.CurrentPage().getParameters().get('id') AND Active__c =: true];
        
        return null;
        
    }
    
    //Generate the PDF Viewer for the Invoice...
    public PageReference generateInvoicePDFMethod()
    {
        invoiceList = new List<Invoice__c>([Select i.Name,i.Total__c, i.Invoice_Type__c, i.Id, i.Date__c, i.Account__r.LicenseNumber__c,i.Account__r.LicenseNumber__r.name, i.Account__r.Name, i.Account__r.Id, i.Account__c, (Select Amount__c, Fee__c,Fee__r.Name, Start_Date__c, End_Date__c, Fee_Type__c, Invoice__c, Location_Booking_Information__c,Name,Location_Booking_Information__r.Location__r.Name,Location__c,Location__r.Name From Invoice_Line_Items__r) From Invoice__c i where i.Id =: Apexpages.CurrentPage().getParameters().get('id')]);
    
        return null;
    }   
    
    //For Generating Receipt Viewer Method...
    public PageReference generateReceiptViewerMethod()
    {
        //CurrentTime= CurrentTime.addhours(4);
        //Getting the Account Id of the Receipt...
        receiptPDFViewerList = new List<Receipt__c>([Select CreatedDate,CreatedByName__c,Total_Amount_on_Invoice__c,Payment_Amount__c, Related_Invoice__r.Invoice_Type__c, Related_Invoice__r.Id,Related_Invoice__r.Name, Related_Invoice__c, Receipt_Type__c, Name, Id, Company__r.LicenseNumber__c,Company__r.LicenseNumber__r.Name, Company__r.Name, Company__r.Id, Company__c,Company__r.LegalStatus__r.Short_Name_English__c, (Select Method__c,Number__c, Amount__c, Bank_Name__c,Date__c  From Payments__r) From Receipt__c where Id =: Apexpages.CurrentPage().getParameters().get('id')]);
        
        System.debug('The Total receipt Numbers are => '+ receiptPDFViewerList.size());
        
        if(receiptPDFViewerList.size() > 0)
        {
            CurrentTimeReceipt= receiptPDFViewerList[0].CreatedDate;
            CurrentTimeReceipt= CurrentTimeReceipt.addhours(4);
            
            string invoiceId = receiptPDFViewerList[0].Related_Invoice__r.Id;
            invoiceLineItemList = new List<Invoice_Line_Item__c>([Select Location__c,Location__r.Name, Name,Amount__c, Fee__c,Fee__r.Name, Start_Date__c, End_Date__c, Fee_Type__c, Invoice__c, Location_Booking_Information__c,Location_Booking_Information__r.Location__r.Name From Invoice_Line_Item__c where Invoice__c =: invoiceId]);
            System.debug('The Invoice Id =>'+ invoiceId );
            System.debug('The Total invoiceLineItemList are => '+ invoiceLineItemList.size());
        
        
        }
        
        //Return the project...
        return null;
    
    }
    
    //For Generating the Tenancy Contract PDF Viewer Method...
    public PageReference generatingAccountTenancyContractPDF()
    {
        //CurrentTime= CurrentTime.addhours(4);
        tenancyContractViewerList =  new List<Tenancy_Contract__c>([Select Tenant__r.LicenseNumber__r.Name,Tenant__r.LicenseNumber__c, Tenant__r.Name, Total_Visas_Available__c, Tenant__c,Tenant__r.authorized_manager__r.name,Tenant__r.authorized_manager__r.nationality__r.name,Tenant__r.authorized_manager__r.passport_number_formula__c, Tenancy_Contract_Start_Date__c, Tenancy_Contract_Expiry_Date__c, Rental_Rate__c, Name, Location_type__c, Location__c, Id, Fee__c, Contract_Status__c,Location__r.Surface_Area__c,Location__r.Rental_Rate__c, Location__r.Name, Location__r.Area__c,Location__r.Area__r.Name, Location__r.Fee__c, Location__r.Area__r.Project_Type__c, Location__r.Current_Tenancy_Contract__c,Location__r.Current_Tenancy_Contract__r.Name, Location__r.Current_Tenancy_Contract__r.Contract_Status__c,Location__r.Current_Tenancy_Contract__r.Location_type__c, Location__r.Current_Tenancy_Contract__r.Rental_Rate__c,Location__r.Current_Tenancy_Contract__r.Tenancy_Contract_Expiry_Date__c, Location__r.Visa_Quota__c, Location__r.Current_Tenancy_Contract__r.Tenancy_Contract_Start_Date__c, Location__r.Current_Tenancy_Contract__r.Total_Visas_Available__c From Tenancy_Contract__c where Id =: Apexpages.CurrentPage().getParameters().get('id')]);
        
        if(tenancyContractViewerList.size() > 0)
        {
            numberToWordString = numberToWordClass.english_number(tenancyContractViewerList[0].Rental_Rate__c);
        
        }
        //Returning the value...
        return null;
        
    }
    
    //For Generating the License Information PDF Viewer....
    public PageReference generatingLicensePDF()
    {
        accountForLicenseList = new Account();
        //CurrentTime= CurrentTime.addhours(4);
        System.debug('The Acount Id for License PDF => '+Apexpages.CurrentPage().getParameters().get('id'));
        //accountForLicenseList = [Select Name,Account_Activity_Category__c,Account_Activity_Category_Arabic__c,Authorized_Manager__r.Arabic_Name__c, Authorized_Manager__r.Nationality__r.Country_Arabic_Name__c,Authorized_Manager__r.Nationality__r.name,License_Issue_Date__c,company_name_arabic__c, License_Expiry_Date__c, LicenseNumber__c,LicenseNumber__r.Name, LegalStatus__r.Name_Arabic__c, LegalStatus__r.Name, LegalStatus__r.Id, LegalStatus__c,LegalStatus__r.Short_Name_English__c, LegalStatus__r.Short_Name_Arabic__c, File_Number__c, Authorized_Manager__r.Passport_Number_Formula__c, Authorized_Manager__r.Nationality__c, Authorized_Manager__r.Name, Authorized_Manager__c,(select Id, Shareholder_English_Name__c,Shareholder__c,Shareholder__r.Arabic_Name__c,Shareholder__r.FirstName,Shareholder__r.LastName,Company__c from Share_Ownerships__r), (Select Id, Location__c,Location__r.name From Location_History__r where Location__r.Location_Status__c != 'Under Cancellation'), (Select Id, Active__c,Activity__c, Activity_Arabic_Name__c, Activity_English_Name__c From Account_Activities__r WHERE Active__c =: true) From Account where Id =: Apexpages.CurrentPage().getParameters().get('id')];
        accountForLicenseList = [Select Name,License_State_Date__c,Company_Establishment_Date__c,Account_Activity_Category__c,Account_Activity_Category_Arabic__c,Authorized_Manager__r.Arabic_Name__c, Authorized_Manager__r.Nationality__r.Country_Arabic_Name__c,Authorized_Manager__r.Nationality__r.name,License_Issue_Date__c,company_name_arabic__c, License_Expiry_Date__c, LicenseNumber__c,LicenseNumber__r.Name, LegalStatus__r.Name_Arabic__c, LegalStatus__r.Name, LegalStatus__r.Id, LegalStatus__c,LegalStatus__r.Short_Name_English__c, LegalStatus__r.Short_Name_Arabic__c, File_Number__c, Authorized_Manager__r.Passport_Number_Formula__c, Authorized_Manager__r.Nationality__c, Authorized_Manager__r.Name, Authorized_Manager__c,(select Id, Shareholder_English_Name__c,Shareholder__c,Shareholder__r.Arabic_Name__c,Shareholder__r.FirstName,Shareholder__r.LastName,Company__c,Sequence_Order__c from Share_Ownerships__r ORDER BY Sequence_Order__c ASC), (Select Id, Tenancy_Contract_Cancellation_Date__c,Location__c,Location__r.name From Location_History__r where Tenancy_Contract_Cancellation_Date__c =: null), (Select Id, Active__c,Activity__c, Activity_Arabic_Name__c, Activity_English_Name__c,Sequence_Order__c From Account_Activities__r WHERE Active__c =: true ORDER BY Sequence_Order__c ASC) From Account where Id =: Apexpages.CurrentPage().getParameters().get('id')];
       
        //Returning the values...
        return null;
        
    }
    
    //For Generating the ChamberPDF Viewer Method...
    public PageReference generatingChamberPDFMethod()
    {
        accountForChamberObject = new Account();
        //CurrentTime= CurrentTime.addhours(4);
        accountForChamberObject = [Select PO_Box__c,Fax,Phone,company_name_arabic__c, Name, License_Application_Type__c, LicenseNumber__r.Name, LicenseNumber__c, LegalStatus__r.Name_Arabic__c, LegalStatus__r.Name,LegalStatus__r.Short_Name_English__c, LegalStatus__r.Short_Name_Arabic__c, LegalStatus__c, Authorized_Manager__r.Passport_Number_Formula__c, Authorized_Manager__r.Arabic_Name__c, Authorized_Manager__r.Gender__c, Authorized_Manager__c, (Select Share_Holder_Country__c,Company__c,Shareholder__r.Passport_Number_Formula__c,Shareholder__r.Gender__c,Shareholder__r.Arabic_Name__c, Shareholder__c, Ownership__c From Share_Ownerships__r), (Select Account__c, Active__c,Activity__c, Activity_Arabic_Name__c, Activity_English_Name__c From Account_Activities__r WHERE Active__c =: true) From Account where Id =: Apexpages.CurrentPage().getParameters().get('id')];
        string amendmentId = Apexpages.CurrentPage().getParameters().get('amendmentId');
        string amendmentIdentifierPartner = Apexpages.CurrentPage().getParameters().get('partner');
        string amendmentIdentifierActivity = Apexpages.CurrentPage().getParameters().get('activity');
        System.debug('The Amendment Id with Parameter => '+ Apexpages.CurrentPage().getParameters().get('amendmentId') + ' && With the Variable => '+ amendmentId );
        if(amendmentId != null)
        {
            chamberPage1Flag = false;
            
            
            chamberPage2Flag = true;
            if(amendmentIdentifierPartner != null)
            {
                chamberPartnerAmendmentFlag = true;
                chamberPage2Flag = false;
                chamberActivityAmendmentFlag= false;
            }
            if(amendmentIdentifierActivity != null)
            {
                chamberActivityAmendmentFlag = true;
                chamberPartnerAmendmentFlag = false;
                chamberPage2Flag = false;
            }
            amendmentForChamberObject = new Amendment__c();
            amendmentForChamberObject = [select Id,New_Company_Name__c,New_Company_Name_Arabic__c ,(SELECT id,name,Account__c,Active__c,Add_Flag__c,Edit_Flag__c,Delete_Flag__c,Activity_Arabic_Name__c,Activity_English_Name__c,Amendment__c,Activity__c FROM Amendment_Activities__r where Active__c =: true AND Delete_Flag__c =: false),(SELECT Id,NAME,Contact__r.Passport_Number_Formula__c,Account__c,Contact__r.Arabic_Name__c,Delete_Flag__c,Contact__r.Gender__c,Contact__c,Contact_Country__c,Ownership__c,Share_Profit__c,Share_Ownership__c,ShareHolder_Name__c FROM Shareholder_Amendments__r where Delete_Flag__c =: false) from Amendment__c where Id =: amendmentId];
            
        }
        //Returning the Values...
        return null;
    }
    
    
    //For Generating the Article of Associations PDF Viewer Method...
    public PageReference generatingArticleOfAssociationPDF()
    {
        try
        {
            //CurrentTime= CurrentTime.addhours(4);
            accountForArticlesObject = new Account();
            accountForArticlesObject = [select  Authorized_Manager__c,Authorized_Manager__r.FirstName,Authorized_Manager__r.LastName, Authorized_Manager__r.Arabic_Name__c,id,name, PO_Box__c,Company_Capital__c,Number_of_Shares__c,company_name_arabic__c,LicenseNumber__c,LicenseNumber__r.Name,Legal_Status__c, LegalStatus__r.Short_Name_English__c, LegalStatus__r.Short_Name_Arabic__c from Account where Id =: Apexpages.CurrentPage().getParameters().get('id')];
            ListShareholders = new List<Wrapper_Shareholders>();
            System.debug('The Company Name => '+ accountForArticlesObject.name);
            
            partyInformationList = new List<Share_Ownership__c>([Select No_of_Shares__c,Share_Profit__c,Shares_Value__c,Shareholder__r.isManagerReference__c,Shareholder__r.Passport_Number_Formula__c, Shareholder__r.Nationality__c, Shareholder__r.Nationality__r.Country_Arabic_Name__c, Shareholder__r.Nationality__r.Name, Shareholder__r.Nationality__r.Id, Shareholder__r.Passport_Expiry_Date__c, Shareholder__r.Passport_Issue_Date__c, Shareholder__r.Passport_Issue_Place__c, Shareholder__r.Passport_Issue_Country__c, Shareholder__r.Passport_Number__c, Shareholder__r.Contact_Type__c, Company__r.LegalStatus__c, Company__r.company_name_arabic__c, Company__r.Name, Company__c, Company__r.Legal_Status__c, Company__r.LegalStatus__r.Short_Name_English__c, Company__r.LegalStatus__r.Short_Name_Arabic__c,Shareholder__r.Arabic_Name__c, Shareholder__r.Address_Arabic__c, Shareholder__r.Address_English__c, Shareholder__r.Gender__c, Shareholder__r.Preferred_Language__c, Shareholder__r.Email, Shareholder__r.Name, Shareholder__r.Salutation, Shareholder__r.FirstName, Shareholder__r.LastName, Shareholder__c, Ownership__c, Name From Share_Ownership__c where Company__c =: Apexpages.CurrentPage().getParameters().get('id')]);
            //
            integer count = 1;
            System.debug('The Party Information List Size =>'+ partyInformationList.size());
            //partyManagerObject = new Share_Ownership__c();
            
            for(Share_Ownership__c partyObject : partyInformationList )
            {
                System.debug('The party Name =>'+ partyObject.Id + ' & the Role is => '+ partyObject.Shareholder__r.Contact_Type__c);
                
                /*if(partyObject.Shareholder__r.Contact_Type__c.contains('Shareholder') == true)
                {
                    System.debug('The party Name in Shareholder=>'+ partyObject.Id);
                    ListShareholders.add(new Wrapper_Shareholders(count++, partyObject));
                    System.debug('The party Name in after Shareholder=>'+ partyObject.Id);
                }
                if(partyObject.Shareholder__r.Contact_Type__c.contains('Manager') == true)        
                {
                    System.debug('The party Name in Manager=>'+ partyObject.Id);
                    partyManagerObject = partyObject;
                }*/ 
                System.debug('The party Name in Shareholder=>'+ partyObject.Id);
                ListShareholders.add(new Wrapper_Shareholders(count++, partyObject));
                System.debug('The party Name in after Shareholder=>'+ partyObject.Id);
            }
                
            //Now Returning the Values....
            return null;
        
        }
        catch(Exception exp)
        {
            System.debug(exp.getMessage());
            
            //Now Returning the Values....
            return null;
        }
    }
    
    //For Shareholder Wrapper Class..
    public class Wrapper_Shareholders
    {
        public Integer SerialNumber {get;set;}
        Public Share_Ownership__c Shareholder {get;set;}
        
        public Wrapper_Shareholders(Integer Serial, Share_Ownership__c record)
        {
            SerialNumber = Serial;
            Shareholder = record;
            
            
            System.debug('...... In a Constructor.....');
        }
    }
    
    
    
    //For Generating the Payment Module Initiator Method....
    public PageReference generatePaymentModule()
    {
        List<Receipt__c> Receipts = [SELECT id,Login_Profile_Name__c, Receipt_PDF_Counter__c,is_Cancelled_Receipt__c, paymentConfirmationFlag__c,name,Receipt_Balance__c,Company__r.Id, company__c, date__c, Receipt_Type__c,Related_Invoice__c,Total_Amount_on_Invoice__c FROM Receipt__c WHERE Id = :ApexPages.CurrentPage().getParameters().get('id')];
        NewPayment = new Payment__c();
        
        ReceiptWrapperList = new List<ReceiptWrapper>();
        
        for(Receipt__c Receipts_trav : Receipts)
        {
            //For Button Rendering Logic...
            if(Receipts_trav.is_Cancelled_Receipt__c == true)
            {
                paymentConfirmationFlag = false;
                confirmationbuttonFlag = false; 
                pdfbuttonFlag = false;
            }
            else if(Receipts_trav.paymentConfirmationFlag__c == true)
            {               
                paymentConfirmationFlag = false;
                confirmationbuttonFlag = false; 
                pdfbuttonFlag = true;
            }
            else
            {
                pdfbuttonFlag = false;
                paymentConfirmationFlag = true;
                confirmationbuttonFlag = true;  
            }   
            receiptObject = Receipts_trav;
            receiptName = Receipts_trav.name;
            NewPayment.Receipt_ID__c = Receipts_trav.id;
            receiptAccountId = Receipts_trav.Company__r.Id;
            receiptBalance = Receipts_trav.Receipt_Balance__c;
            //ReceiptWrapperList.Add(new ReceiptWrapper(Receipts_trav.name, Receipts_trav.Receipt_Type__c, Receipts_trav.id));
            ReceiptWrapperList.Add(new ReceiptWrapper(Receipts_trav.name, Receipts_trav.Receipt_Type__c, Receipts_trav.Total_Amount_on_Invoice__c, Receipts_trav.id));
        }
        
        for(ReceiptWrapper ReceiptWrapper_trav : ReceiptWrapperList)
        {
            try
            {
                ReceiptWrapper_trav.Payments = [SELECT id, name, Amount__c, Bank_Name__c, Date__c, Method__c, Number__c, Receipt_ID__c FROM Payment__c WHERE Receipt_ID__c = :ReceiptWrapper_trav.RecordId];
                
                /*for(Payment__c Payment_trav : ReceiptWrapper_trav.Payments)
                {
                    //receiptBalance = receiptBalance - Payment_trav.Amount__c;
                    receiptBalance = Payment_trav.Amount__c - receiptBalance;
                }
                
                if(receiptBalance < 0)
                    receiptBalance = 0;*/
                /*for(Payment__c Payment_trav : ReceiptWrapper_trav.Payments)
                {
                    
                    //ReceiptWrapper_trav.ReceiptBalance = ReceiptWrapper_trav.ReceiptBalance - Payment_trav.Amount__c;
                     System.debug('The Receipt Balance in Payments  => ' + receiptBalance  );
                     System.debug('The Payments Amount => ' +  Payment_trav.Amount__c);
                    receiptBalance = receiptBalance - Payment_trav.Amount__c;
                    System.debug('The Receipt Balance after Payments  => ' + receiptBalance  );
                }
                
                if(receiptBalance < 0)
                    receiptBalance = 0;*/
                
                
                
            }
            catch(System.Exception er)
            {
                ReceiptWrapper_trav.Payments = new List<Payment__c>();
            }
        }
        
        CreatedDate = System.Today().format();
        actionbuttonADD = true;
        actionbuttonEdit = false;
        
    
        return null;   
    }
    
    
    public string CreatedDate {get; set;}
    
    Public Boolean InitializerFlag = true;
    //System.debug('The InitializerFlag Value Before => '+ InitializerFlag );
    public string check1 {get; set;}
    public PageReference additems()
    {
        check1 = 'entered';
        NewPayment.Receipt_ID__c = ApexPages.CurrentPage().getParameters().get('id');
        
        try
        {
            Decimal BalanceCheck = 0.0;
            for(ReceiptWrapper ReceiptWrapper_trav : ReceiptWrapperList)
            {
                System.debug('The Receipt Wrapper Id => '+ ReceiptWrapper_trav.RecordID);
                check1 = ReceiptWrapper_trav.RecordID;
                System.Debug(ReceiptWrapper_trav.RecordID + ' - ' + NewPayment.Receipt_ID__c);
                check1 = ReceiptWrapper_trav.RecordID + '-' + NewPayment.Receipt_ID__c;
                if(ReceiptWrapper_trav.RecordID == NewPayment.Receipt_ID__c)
                {
                    check1 = 'testing';
                    System.debug('The New Payment Amount => '+ NewPayment.Amount__c);
                    //ReceiptWrapper_trav.ReceiptBalance = ReceiptWrapper_trav.ReceiptBalance - NewPayment.Amount__c;
                    
                    if(NewPayment.Amount__c == null)
                        NewPayment.Amount__c = 0;
                    
                    receiptBalance = ReceiptWrapper_trav.ReceiptAmount;
                    receiptBalance = receiptBalance - NewPayment.Amount__c;
                    //receiptBalance = receiptBalance + NewPayment.Amount__c;
                    
                    System.debug('The New Payment Value before Validation In Add Item => '+ NewPayment.Amount__c);
                    System.debug('The Receipt Balance before Validation In Add Item => '+ receiptBalance);
                    
                    if(receiptBalance < 0)
                        receiptBalance = 0;
                    
                    //if(ReceiptWrapper_trav.ReceiptBalance < 0)
                    if(receiptBalance  < 0)
                    {
                        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Provided amount is more than balance amount');
                        ApexPages.addMessage(msg);
                        break;
                    }
                    //else if(ReceiptWrapper_trav.Payments.size() < 12)
                    if(ReceiptWrapper_trav.Payments.size() < 12)
                    {
                        System.Debug('Before Insert the Payment');
                        insert(NewPayment);
                        check1 = NewPayment.Id;
                        NewPayment = new Payment__c();
                    }
                    else
                    {
                        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'More than twelve(12) payments are not allowed for Receipt #: ' + ReceiptWrapper_trav.ReceiptNumber + '. Please adjust the balance amount in existing payments.');
                        ApexPages.addMessage(msg);
                        break;
                        return null;
                        
                    }
                }
            }
            for(ReceiptWrapper ReceiptWrapper_trav : ReceiptWrapperList)
            {
                try
                {
                    ReceiptWrapper_trav.Payments = [SELECT id, name, Amount__c,  Bank_Name__c,Date__c, Method__c, Number__c, Receipt_ID__c FROM Payment__c WHERE Receipt_ID__c = :ReceiptWrapper_trav.RecordId];
                    //ReceiptWrapper_trav.ReceiptBalance = ReceiptWrapper_trav.ReceiptAmount;
                    receiptBalance = ReceiptWrapper_trav.ReceiptAmount;
                    for(Payment__c Payment_trav : ReceiptWrapper_trav.Payments)
                    {
                        //ReceiptWrapper_trav.ReceiptBalance = ReceiptWrapper_trav.ReceiptBalance - Payment_trav.Amount__c;
                        receiptBalance = receiptBalance - Payment_trav.Amount__c;
                    }
                    
                    if(receiptBalance < 0)
                        receiptBalance = 0;
                }
                catch(System.Exception er)
                {
                    ReceiptWrapper_trav.Payments = new List<Payment__c>();
                }
            }
            //refreshPage = true;
            
            return null;
        }
        catch(System.Exception er)
        {
            //ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, er.getMessage() + ' - Line Number: ' + er.getlinenumber());
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, er.getMessage());
            ApexPages.addMessage(msg);
            return null;
        }
    }
    
    public void EditAllow()
    {
        System.debug('The RowIndex Value => '+ RowIndex);
        System.debug('The Last Index Of ":" => '+ RowIndex.lastIndexof(':'));
        System.debug('The Last Index Of "J" => '+ RowIndex.lastIndexof('j'));
        string valindex = RowIndex.substring(RowIndex.lastIndexof(':') - 1, RowIndex.lastIndexof(':'));
        string val2index = RowIndex.substring(RowIndex.lastIndexof('j') - 2, RowIndex.lastIndexof('j') - 1);
        RowIndex = valindex;
        
        System.debug('The val1Index => '+ valindex);
        System.debug('The val2Index => j_id0:MainForm:j_id50:0:j_id52:0:EDITID'+ val2index);
        
        integer indexA = integer.valueof(valindex);
        integer indexB = integer.valueof(val2index);
        NewPayment = new Payment__c();
        NewPayment = ReceiptWrapperList[indexB].Payments.get(indexA);
        System.debug('The New Payment with wrapper Class');
        //ReceiptWrapperList[indexB].ReceiptBalance = ReceiptWrapperList[indexB].ReceiptBalance + NewPayment.Amount__c;
        
        if(NewPayment.Amount__c == null)
            NewPayment.Amount__c = 0;
        System.debug('The New Payment Amount On Edit => '+ NewPayment.Amount__c);
        receiptBalance = receiptBalance + NewPayment.Amount__c;
        
        if(receiptBalance < 0)
            receiptBalance = 0;
                        
        actionbuttonADD = false;
        actionbuttonEdit = true;

    }
    
    public void DelAllow()
    {
        string valindex = RowIndex.substring(RowIndex.lastIndexof(':') - 1, RowIndex.lastIndexof(':'));
        string val2index = RowIndex.substring(RowIndex.lastIndexof('j') - 2, RowIndex.lastIndexof('j') - 1);
        RowIndex = valindex;
        
        integer indexA = integer.valueof(valindex);
        integer indexB = integer.valueof(val2index);
        
        System.debug('The Index A => '+ indexA);
        System.debug('The Index B => '+ indexB);
        System.debug('The Total Receipt Wrapper Size => '+ ReceiptWrapperList.size());
        System.debug('The Total Receipt Wrapper Payment Size => '+ ReceiptWrapperList[indexB].Payments.size());
        Payment__c PT = ReceiptWrapperList[indexB].Payments.get(indexA);
        
        try
        {
            delete(PT);
            NewPayment = new Payment__c();
            for(ReceiptWrapper ReceiptWrapper_trav : ReceiptWrapperList)
            {
                try
                {
                    //ReceiptWrapper_trav.ReceiptBalance = ReceiptWrapper_trav.ReceiptAmount;
                    receiptBalance = ReceiptWrapper_trav.ReceiptAmount;
                    ReceiptWrapper_trav.Payments = [SELECT id, name, Amount__c,Bank_Name__c,  Date__c, Method__c, Number__c, Receipt_ID__c FROM Payment__c WHERE Receipt_ID__c = :ReceiptWrapper_trav.RecordId];
                    for(Payment__c Payment_trav : ReceiptWrapper_trav.Payments)
                    {
                        //ReceiptWrapper_trav.ReceiptBalance = ReceiptWrapper_trav.ReceiptBalance - Payment_trav.Amount__c;
                        receiptBalance = receiptBalance - Payment_trav.Amount__c;
                    }
                    
                    if(receiptBalance < 0)
                        receiptBalance = 0;
                }
                catch(System.Exception er)
                {
                    ReceiptWrapper_trav.Payments = new List<Payment__c>();
                }
            }
            
        }
        catch(System.Exception er)
        {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, er.getMessage());
            ApexPages.addMessage(msg);
        }
        
        actionbuttonADD = true;
        actionbuttonEdit = false;
        //refreshPage = true;
    }
    
    public string updateitemlist()
    {
        try
        {
            for(ReceiptWrapper ReceiptWrapper_trav : ReceiptWrapperList)
            {
                check1 = ReceiptWrapper_trav.RecordID;
                System.Debug(ReceiptWrapper_trav.RecordID + ' - ' + NewPayment.Receipt_ID__c);
                Decimal BalanceCheck = 0;
                if(ReceiptWrapper_trav.RecordID == NewPayment.Receipt_ID__c)
                {
                    //BalanceCheck = ReceiptWrapper_trav.ReceiptBalance - NewPayment.Amount__c;
                    BalanceCheck = receiptBalance - NewPayment.Amount__c;
                    if(BalanceCheck < 0)
                    {
                        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Provided amount is more than balance amount');
                        ApexPages.addMessage(msg);
                        return null;
                    }
                    else
                    {
                        update(NewPayment);
                        for(ReceiptWrapper ReceiptWrapper_trav1 : ReceiptWrapperList)
                        {
                            try
                            {
                                ReceiptWrapper_trav1.Payments = [SELECT id, name, Amount__c, Bank_Name__c, Date__c, Method__c, Number__c, Receipt_ID__c FROM Payment__c WHERE Receipt_ID__c = :ReceiptWrapper_trav1.RecordId];
                                //ReceiptWrapper_trav1.ReceiptBalance = ReceiptWrapper_trav1.ReceiptAmount;
                                receiptBalance = ReceiptWrapper_trav1.ReceiptAmount;
                                for(Payment__c Payment_trav : ReceiptWrapper_trav1.Payments)
                                {
                                    //ReceiptWrapper_trav1.ReceiptBalance = ReceiptWrapper_trav1.ReceiptBalance - Payment_trav.Amount__c;
                                    receiptBalance = receiptBalance - Payment_trav.Amount__c;
                                }
                                
                                if(receiptBalance < 0 )
                                    receiptBalance = 0;
                                
                            }
                            catch(System.Exception er)
                            {
                                ReceiptWrapper_trav1.Payments = new List<Payment__c>();
                            }
                        }
                        NewPayment = new Payment__c();
                        actionbuttonADD = true;
                        actionbuttonEdit = false;
                        //refreshPage = true;
                    }
                    break;
                }
            }
        }
        catch(System.Exception er)
        {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, er.getMessage());
            ApexPages.addMessage(msg);
        }

        return null;
    }
    
    /*public List<SelectOption> getReceiptList()
    {
        List<SelectOption> options = new List<SelectOption>();
        
        List<Receipt__c> Receipts = [SELECT id, name FROM Receipt__c WHERE Id =:ApexPages.CurrentPage().getParameters().get('id')];
        options.add(new SelectOption('', '-- SELECT RECEIPT --'));
        for(Receipt__c Receipt_trav : Receipts)
        {
            options.add(new SelectOption(Receipt_trav.id, Receipt_trav.name));
        }
        
        return options;
    }*/
    
    public void cancelEdit()
    {
        try
        {
            NewPayment = new Payment__c();
            for(ReceiptWrapper ReceiptWrapper_trav : ReceiptWrapperList)
            {
                try
                {
                    ReceiptWrapper_trav.Payments = [SELECT id, name, Amount__c, Bank_Name__c, Date__c, Method__c, Number__c, Receipt_ID__c FROM Payment__c WHERE Receipt_ID__c = :ReceiptWrapper_trav.RecordId];
                    //ReceiptWrapper_trav1.ReceiptBalance = ReceiptWrapper_trav1.ReceiptAmount;
                    receiptBalance = ReceiptWrapper_trav.ReceiptAmount;
                    for(Payment__c Payment_trav : ReceiptWrapper_trav.Payments)
                    {
                        //ReceiptWrapper_trav1.ReceiptBalance = ReceiptWrapper_trav1.ReceiptBalance - Payment_trav.Amount__c;
                        receiptBalance = receiptBalance - Payment_trav.Amount__c;
                    }
                    
                    if(receiptBalance < 0 )
                        receiptBalance = 0;
                
                
                }
                catch(System.Exception er)
                {
                    ReceiptWrapper_trav.Payments = new List<Payment__c>();
                }
            }
        }
        catch(System.Exception er)
        {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, er.getMessage());
            ApexPages.addMessage(msg);
        }
        actionbuttonADD = true;
        actionbuttonEdit = false;
    }
    
    Public PageReference ProceedToNextStep()
    {
        Boolean VerificationFlag = true;
        String NonZeroReceipt = '';
        for(ReceiptWrapper ReceiptWrapper_trav : ReceiptWrapperList)
        {
            System.debug('The receipt Balance Item => '+ ReceiptWrapper_trav.ReceiptBalance);
            //if(ReceiptWrapper_trav.ReceiptBalance != 0.0)
            if(receiptBalance != 0.0)
            {
                VerificationFlag = false;
                NonZeroReceipt = ReceiptWrapper_trav.ReceiptNumber;
                break;
            }
        }
        System.debug('The verification Flag => '+ VerificationFlag);
        if(VerificationFlag)
        {
            if(receiptObject.Receipt_PDF_Counter__c == null)
                receiptObject.Receipt_PDF_Counter__c = 0;
                
            if(receiptObject.Receipt_PDF_Counter__c > 0 && (receiptObject.Login_Profile_Name__c != 'System Administrator' && receiptObject.Login_Profile_Name__c != 'SmartPaper BPM: 24 License - Finance User' && receiptObject.Login_Profile_Name__c != 'SmartPaper BPM: 25 Finance User - Receipts' && receiptObject.Login_Profile_Name__c != 'SmartPaper BPM: 25 Finance User - Inquires'))
            {
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Please Contact Finance Department to generate a new Receipt PDF');
                ApexPages.addMessage(msg);
                return null;
            }   
                
                
            receiptObject.Receipt_PDF_Counter__c = receiptObject.Receipt_PDF_Counter__c + 1;
            update receiptObject;
            
            
            redirectToReceiptPdfFlag = true;
            refreshPage = true;
            /*PageReference pg = new PageReference('/apex/vfp_ReceiptPDF?id=' + ApexPages.CurrentPage().getParameters().get('id'));
            pg.setRedirect(true);
            return pg;*/
        }
        else
        {
            refreshPage = false;
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'The Balance amount for Receipt #: ' + NonZeroReceipt + ' should be zero to continue');
            ApexPages.addMessage(msg);
        }
        return null;
    }
    Public PageReference redirectToReceiptPage()
    {
        /*PageReference pg = new PageReference('/' + ApexPages.CurrentPage().getParameters().get('id'));
        pg.setRedirect(true);
        return pg;*/
        
        
        Boolean VerificationFlag = true;
        String NonZeroReceipt = '';
        for(ReceiptWrapper ReceiptWrapper_trav : ReceiptWrapperList)
        {
            System.debug('The receipt Balance Item => '+ ReceiptWrapper_trav.ReceiptBalance);
            //if(ReceiptWrapper_trav.ReceiptBalance != 0.0)
            if(receiptBalance != 0.0)
            {
                VerificationFlag = false;
                NonZeroReceipt = ReceiptWrapper_trav.ReceiptNumber;
                break;
            }
        }
        System.debug('The verification Flag => '+ VerificationFlag);
        if(VerificationFlag)
        {
            
            
            /*PageReference pg = new PageReference('/apex/vfp_ReceiptPDF?id=' + ApexPages.CurrentPage().getParameters().get('id'));
            pg.setRedirect(true);
            return pg;*/
            
            receiptObject.paymentConfirmationFlag__c = true;
            update receiptObject;
            
            //Now Update the Flags...
            paymentConfirmationFlag = true;
            confirmationButtonFlag = false;
            pdfButtonFlag = true;
            refreshPage = true;
            
            //Old Approach...
            /*Receipt__c receiptObject = new Receipt__c();
            receiptObject = [select Id,paymentConfirmationFlag__c FROM Receipt__c where Id =: ApexPages.CurrentPage().getParameters().get('id')];
            
            if(receiptObject != null)
            {
                receiptObject.paymentConfirmationFlag__c = true;
                update receiptObject;
                
                //Now Update the Flags...
                paymentConfirmationFlag = true;
                confirmationButtonFlag = false;
                pdfButtonFlag = true;
                refreshPage = true;
                
              
            }*/
        }
        else
        {
            refreshPage = false;
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'The Balance amount for Receipt #: ' + NonZeroReceipt + ' should be zero to continue');
            ApexPages.addMessage(msg);
        }
        
        
        //Now Return the Values...
        return null;    
            
        

    }
    //Receipt Wrapper Class..
    class ReceiptWrapper
    {
        Public String ReceiptNumber {get; set;}
        Public String ReceiptGroup {get; set;}
        Public Decimal ReceiptAmount {get; set;}
        Public Decimal ReceiptBalance {get; set;}
        Public ID RecordId {get; set;}
        
        Public List<Payment__c> Payments {get; set;}
        
        public ReceiptWrapper(String RNumber, String RGroup, Decimal RAmount, ID RID)
        {
            ReceiptNumber = RNumber;
            ReceiptGroup = RGroup;
            ReceiptAmount = RAmount;
            ReceiptBalance = RAmount;
            RecordId = RID;
        }
        
        /*public void calculatebalance()
        {
            Decimal PaymentsSum = 0.0;
            
            for(Payment__c Payment_trav : Payments)
            {
                PaymentsSum = PaymentsSum + Payment_trav.Amount__c;
            }
            
            ReceiptBalance = ReceiptBalance - PaymentsSum;
        }*/
    }
    
    
    
}